package groupon.common.util;

import groupon.commom.model.UserEmail;

import java.util.HashMap;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class GrouponMailSender {

	private JavaMailSender mailSender;
	private VelocityEngine velocityEngine;
	
	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	public void sendMail(final UserEmail user,final String subject) {
	      MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
	            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
	            message.setFrom(AppConfiguration.getEmailSystem());
	            message.setTo(user.getEmail());
	            message.setSubject(subject);
	            Map model = new HashMap();
	            model.put("user", user);
	            String text = VelocityEngineUtils.mergeTemplateIntoString(
	               velocityEngine, "META-INF/template/create-user.vm", model);
	            message.setText(text, true);
	         }
	      };
	      try {
	    	  this.mailSender.send(preparator);
		} catch (Exception e) {
			e.printStackTrace();
		}
	   }
	
	 
}
